package com.aoasaa;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;



import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.aoasaa.CreatingTextNotes.MyAsyncTask123;
import com.sendingFBpost.FBAppActivity;
import com.userrequestdtos.FileInfoStoringDTO;
import com.userrequestdtos.ViewingCategoryAndTitleDTO;
import com.userutils.WSConnectionFile;
import com.userutils.WSConnectionStrings;




import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Toast;

public class UploadingDocumentTOPHP extends Activity { 
	public SharedPreferences sp_obj;
	public Editor editor_obj;
	String wsresponse;
	/** Called when the activity is first created. */
	@Override    
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
		setContentView(R.layout.uploadprocessfile); 
    
		// accessing shared preference     
		sp_obj=getSharedPreferences("ArchiveApp",MODE_WORLD_WRITEABLE);
		editor_obj=sp_obj.edit();

		new MyAsyncTask123().execute();  

	}
	// inner class  For Network Connection i.e, for Web service connection
	class MyAsyncTask123 
	extends AsyncTask<Void, String, String>
	{
 
		HttpURLConnection connection = null; 
		DataOutputStream outputStream = null;
		DataInputStream inputStream = null; 

		// String pathToOurFile = "/data/testing123.txt";
		String pathToOurFile=sp_obj.getString("uploadsessionfileurl", ""); 
		String urlServer = "http://10.0.2.2:88/ArchiveAppFiles_upload.php";
		String lineEnd = "\r\n"; 
		String twoHyphens = "--";
		String boundary =  "*****"; 

		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;    
		int maxBufferSize = 1*1024*1024; 

		@Override
		protected void onPostExecute(String response) 
		{
			 Toast.makeText(UploadingDocumentTOPHP.this,response,Toast.LENGTH_LONG).show();
			 String[] res=UserXMLParsingFile.responseOperation(UploadingDocumentTOPHP.this,response, "", "");
			 Toast.makeText(UploadingDocumentTOPHP.this,""+res,Toast.LENGTH_LONG).show();
			 
			 // navigating back to home screen.
			  
		}
		@Override 
		protected String doInBackground(Void... params) {
			// your network operation

			try      
			{
				FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

				URL url = new URL(urlServer);
				connection = (HttpURLConnection) url.openConnection();

				// Allow Inputs & Outputs  
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setUseCaches(false);

				// Enable POST method
				connection.setRequestMethod("POST");
  
				connection.setRequestProperty("Connection", "Keep-Alive");
				connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

				outputStream = new DataOutputStream( connection.getOutputStream() );
				outputStream.writeBytes(twoHyphens + boundary + lineEnd);
				outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
				outputStream.writeBytes(lineEnd);

				bytesAvailable = fileInputStream.available();  
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];

				// Read file 
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				while (bytesRead > 0)
				{
					outputStream.write(buffer, 0, bufferSize);
					bytesAvailable = fileInputStream.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fileInputStream.read(buffer, 0, bufferSize);
				}

				outputStream.writeBytes(lineEnd);
				outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

				// Responses from the server (code and message)
				int    serverResponseCode = connection.getResponseCode();
				String  serverResponseMessage = connection.getResponseMessage();

				fileInputStream.close();  
				outputStream.flush();
				outputStream.close();
				BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
					final String uploadcheck=rd.readLine().trim();   
					if(uploadcheck.equals("file uploaded"))                   
					{
						rd.close();
						UploadingDocumentTOPHP.this.runOnUiThread(new Runnable() {
							  public void run() {
								  Toast.makeText(UploadingDocumentTOPHP.this,uploadcheck,Toast.LENGTH_LONG).show();
							  }
							});  
						
						if(sp_obj.getString("checkingSAVEorFB", "NOA").equals("FB"))
						{
							UploadingDocumentTOPHP.this.runOnUiThread(new Runnable() {
								  public void run() {
									  Toast.makeText(UploadingDocumentTOPHP.this, "Uploaded for sharing on FB", Toast.LENGTH_LONG).show();
								  }
								});  
							
						     
		                             
						// FB LOGIC
							
							String usermessage=sp_obj.getString("selectedfiletitle", "")+" \n "+sp_obj.getString("selectedfilenotes", "");
							
							Intent intent = new Intent(UploadingDocumentTOPHP.this,FBAppActivity.class);
						    intent.putExtra("facebookMessage", usermessage);
						    startActivity(intent); 
						}
						else
						{     
	                    String username=sp_obj.getString("username", "");
						String filename=sp_obj.getString("SelectedFile", "");
						String filecategory=sp_obj.getString("selectedfilecategory", "");
						String filetitle=sp_obj.getString("selectedfiletitle", "");
						String filenotes=sp_obj.getString("selectedfilenotes", "");
						    
						// has to change dynamically  file type image, text or audio
						FileInfoStoringDTO obj_fileinfosaving=new FileInfoStoringDTO("sharan","image",filename,filecategory,filetitle,filenotes);
						 
						wsresponse=WSConnectionFile.wsConn(obj_fileinfosaving, "obj_fileinfosaving", 
								WSConnectionStrings.METHOD_FILESAVING,
								WSConnectionStrings.NAMESPACE+WSConnectionStrings.METHOD_FILESAVING);
					   // navigating to home screen logic
						
					}   
			}
					else                                
					{
						UploadingDocumentTOPHP.this.runOnUiThread(new Runnable() {
							  public void run() {
								  Toast.makeText(UploadingDocumentTOPHP.this,"unable to upload,try again !!!!!",Toast.LENGTH_LONG).show();
							  }
							});
						
						// should navigate back to previous screen logic	
					}	
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}

			return wsresponse;     
		}        
	}
} 